package com.dsz.usercenter.job;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsz.usercenter.model.domain.User;
import com.dsz.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PreCacheJob {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserService userService;
    @Resource
    private RedissonClient redissonClient;

    @Scheduled(cron = "0 41 23 * * ?")
    public void loadRecommendUsers() {
        RLock lock = redissonClient.getLock("yupao:precachejob:docache:lock");
        try {
            if (lock.tryLock(0, -1, TimeUnit.SECONDS)) {
                ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
                //缓存中没有就查数据库
                String key = String.format("yupao:user:recommend:%s", 30);
                Page<User> userPage = new Page<>(0, 10);
                Page<User> page = userService.page(userPage);
                List<User> records = page.getRecords();
                List<User> userList = records.stream().map(userService::getSafetyUser).collect(Collectors.toList());
                //添加到缓存
                try {
                    opsForValue.set(key, userList, 30, TimeUnit.SECONDS);
                } catch (Exception e) {
                    log.error("添加缓存失败", e);
                }
            }
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        } finally {
            //只能释放自己的锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
